package com.yeheng.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import javax.sql.DataSource;

/**
 * @PackgeName: com.yeheng.config
 * @ClassName: RootConfig
 * @Author: YH
 * Date: 2020/12/31 22:25
 * project name: homework1
 * @Version:
 * @Description:
 */
@Configuration
@ComponentScan("com.yeheng.service")
@EnableTransactionManagement
@MapperScan("com.yeheng.mapper")//注解代替mapperscannerconfiguration
public class RootConfig {



    @Bean//消息源
    public DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUsername("root");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/company?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&allowMultiQueries=true");
        ds.setPassword("yh996311");
        return ds;
    }

    @Bean
    public SqlSessionFactoryBean getssf(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);
        ssfb.setTypeAliasesPackage("com.yeheng.entity;com.yeheng.dto");
        //配置类形式的mybatis配置类
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //日志插件
        configuration.setLogImpl(StdOutImpl.class);
        //新增返回主键值
        configuration.setUseGeneratedKeys(true);
        //配置分页插件
        ssfb.setPlugins(new Interceptor[]{new PageInterceptor()});
        ssfb.setConfiguration(configuration);
        return ssfb;
    }
    


    @Bean//事务管理器
    public DataSourceTransactionManager manager(DataSource ds){
        DataSourceTransactionManager datas = new DataSourceTransactionManager();
        datas.setDataSource(ds);
        return datas;
    }
}
